﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZQNB.BaseLib.Core.Models;
using ZQNB.Common.Logs;

namespace ZQNB.BaseLib.Core.Services
{
    public class SiteHealthStatusService : ISiteHealthStatusService
    {
        private readonly CoreDataHelper _fileDbHelper;

        public SiteHealthStatusService(CoreDataHelper fileDbHelper)
        {
            _fileDbHelper = fileDbHelper;
        }

        public IList<SiteHealthStatus> GetAllSiteHealthStatuses()
        {
            IList<SiteHealthStatus> siteHealthStatuses = _fileDbHelper.Read<SiteHealthStatus>();
            return siteHealthStatuses.OrderByDescending(x => x.ApplicationStartAt).ToList();
        }

        public SiteHealthStatus GetCurrentSiteHealthStatus()
        {
            IList<SiteHealthStatus> siteHealthStatuses = _fileDbHelper.Read<SiteHealthStatus>();
            SiteHealthStatus currentOne = siteHealthStatuses
                .OrderByDescending(x => x.ApplicationStartAt)
                .FirstOrDefault(x => x.ApplicationEndAt == null);

            return currentOne;
        }

        public void ApplicationStart()
        {
            IList<SiteHealthStatus> siteHealthStatuses = _fileDbHelper.Read<SiteHealthStatus>();
            SiteHealthStatus currentOne = new SiteHealthStatus();
            currentOne.ApplicationStartAt = DateTime.Now;
            //log
            LogMessage("ApplicationStartAt " + currentOne.ApplicationStartAt);

            siteHealthStatuses.Add(currentOne);
            _fileDbHelper.Save(siteHealthStatuses);
        }

        public void ApplicationEnd()
        {
            IList<SiteHealthStatus> siteHealthStatuses = _fileDbHelper.Read<SiteHealthStatus>();
            SiteHealthStatus currentOne = siteHealthStatuses
                .OrderByDescending(x => x.ApplicationStartAt)
                .FirstOrDefault(x => x.ApplicationEndAt == null);

            if (currentOne != null)
            {
                currentOne.ApplicationEndAt = DateTime.Now;
                //log
                LogMessage("ApplicationEndAt " + currentOne.ApplicationEndAt);
                _fileDbHelper.Save(siteHealthStatuses);
            }
        }

        private void LogMessage(string message)
        {
            var logger = this.GetLogger();
            logger.Debug(message);
        }

    }
}
